package shiro;

import java.util.Set;

import org.apache.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import appbase.utils.JsonUtil;
import dshop.model.User;
import dshop.model.permission.PermissionUser;

public class UserRealm extends AuthorizingRealm{

	private static Logger log = Logger.getLogger(UserRealm.class);
	
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException 
	{
		UsernamePasswordToken upToken = (UsernamePasswordToken)token;
		String username = upToken.getUsername();
		String password = new String(upToken.getPassword());
		
		log.info("登录验证，从数据库读取数据_" + username);
		
		User user = User.findBy(username, User.ROLE_ADMIN);
		if (user == null || !User.checkPass(User.encryptPass(password, user.getStr("salt")), user.getStr("password"))) 
		{
			throw new AuthenticationException("账号／密码不正确");
		}
		AuthenticationInfo info = new SimpleAuthenticationInfo(username, password.toCharArray(), getName());
		return info;
	}
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) 
	{
		String account = principals.toString();
		
		log.info("权限验证，从数据库读取数据_" + account);
		
		User user = User.findBy(account, User.ROLE_USER);
		
		SimpleAuthorizationInfo authorInfo = new SimpleAuthorizationInfo();
		if (user != null) 
		{
			Set<String> permSet = PermissionUser.getPermSet(user.getInt("userId"));
			if (permSet != null && !permSet.isEmpty()) 
			{
				authorInfo.addStringPermissions(permSet);
			}
			
			log.info(JsonUtil.toJson(permSet));
		}
		return authorInfo;
	}

}
